package com.anjufang.controller.system;

import java.util.List;
import java.util.Map;

import com.anjufang.utils.validator.Assert;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import com.anjufang.controller.BaseController;
import com.anjufang.entity.GroupDetail;
import com.anjufang.entity.GroupInfo;
import com.anjufang.mapper.GroupInfoMapper;
import com.anjufang.service.system.GroupInfoService;
import com.anjufang.utils.Result;
import com.anjufang.utils.page.PageUtils;
import com.anjufang.utils.page.Query;

@RestController
@RequestMapping("/sys/groupInfo/")
public class GroupInfoController extends BaseController {

	@Autowired
	private GroupInfoService groupInfoService;
	
	@Autowired
	private GroupInfoMapper groupInfoMapper;
	
	/**
	 * 所有分组
	 */
	@RequestMapping(value = LIST)
    public PageUtils list(@RequestParam Map<String, Object> params) {
        // 查询列表数据
        Query query = new Query(params);
        List<GroupInfo> userList = groupInfoService.queryList(query);
        int total = groupInfoService.queryTotal(query);
        PageUtils pageUtil = new PageUtils(userList, total, query.getLimit(), query.getPage());

        return pageUtil;
    }
	
	/**
	 * 创建分组
	 */
	@RequestMapping("import")
	public Result importGroupInfo(String startTime, String longTime, String groupSize) throws Exception {

		if(longTime == null || longTime.length() < 1) {
			longTime = "0";
		}
		int longTime_ = Integer.parseInt(longTime);
		int groupSize_ = Integer.parseInt(groupSize);

		if(startTime.length() < 5) return Result.error("开始时间不能为空");
		
		//分组至少要大于1人
		if( groupSize_ > 0 ) {
			return groupInfoService.insert(startTime, longTime_, groupSize_);
		} else {
			return Result.error("每组人数不能少于1人");
		}
		
	}

	@GetMapping("info")
	public Result info(Long id) {
		Assert.isNull(id, "id不能为空");
		return Result.ok().put("groupInfo", new GroupInfo().selectById(id));
	}

	/**
	 * 逻辑删除
	 */
	@RequestMapping("edit")
	public Result editGroupInfo(@RequestBody GroupInfo groupInfo) throws Exception {
		groupInfo.updateById();
		return Result.ok();
	}

	/**
	 * 逻辑删除
	 */
	@RequestMapping("delete")
	public Result deleteGroupInfo() {

		if (new GroupDetail().selectCount("is_deleted = {0}", 0) > 0) return Result.error("分组内已有用户，不能重新分组");
	
		groupInfoMapper.deleteAll();	
		return Result.ok();
		
	}
	
}
